import csv
import logging
def save_feature_data_to_csv(data, filename):
    """保存特征提取后的数据"""
    fieldnames = [
        'id', 'sentiment', 'sentiment_magnitude', 'keywords', 
        'alert_type', 'text_length', 'has_media'
    ]
    
    try:
        with open(filename, 'w', newline='', encoding='utf-8-sig') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()
            
            for post in data:
                # 如果特征被存储在特定位置
                alert_info = post.get('alert_type', {})
                if isinstance(alert_info, dict):
                    alert_type = alert_info.get('type', '其他')
                else:
                    alert_type = alert_info
                
                row = {
                    'id': post.get('id', ''),
                    'sentiment': post.get('sentiment', 0.0),
                    'sentiment_magnitude': post.get('sentiment_magnitude', 0.0),
                    'keywords': ';'.join(post.get('keywords', [])),
                    'alert_type': alert_type,
                    'text_length': post.get('text_length', 0),
                    'has_media': int(post.get('has_media', False))
                }
                writer.writerow(row)
                
        return True
    except Exception as e:
        logging.error(f"特征数据保存失败: {str(e)}")
        return False